package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.waikuai.shop.entity.ProductReview;
import com.waikuai.shop.mapper.ProductReviewMapper;
import com.waikuai.shop.service.ProductReviewService;
import com.waikuai.shop.vo.ProductReviewVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品评价服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, ProductReview>
        implements ProductReviewService {

    private final ProductReviewMapper productReviewMapper;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<ProductReviewVO> getReviewPage(Page<ProductReview> page, Long productId, Integer status) {
        try {
            IPage<ProductReview> reviewPage = productReviewMapper.selectReviewPageByProductId(page, productId, status);
            
            IPage<ProductReviewVO> result = new Page<>(reviewPage.getCurrent(), reviewPage.getSize(), reviewPage.getTotal());
            List<ProductReviewVO> records = reviewPage.getRecords().stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
            result.setRecords(records);
            
            return result;
        } catch (Exception e) {
            log.error("分页查询商品评价列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("分页查询商品评价列表失败");
        }
    }

    @Override
    public List<ProductReviewVO> getReviewsByProductId(Long productId, Integer status, Integer limit) {
        try {
            List<ProductReview> reviews = productReviewMapper.selectReviewsByProductId(productId, status, limit);
            return reviews.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取商品评价列表失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addReview(Long userId, Long productId, Integer rating, String content, List<String> images) {
        try {
            if (rating == null || rating < 1 || rating > 5) {
                log.warn("评分无效，评分: {}", rating);
                return false;
            }

            ProductReview review = new ProductReview();
            review.setUserId(userId);
            review.setProductId(productId);
            review.setRating(rating);
            review.setContent(content);
            review.setStatus(1); // 默认审核通过

            if (images != null && !images.isEmpty()) {
                try {
                    String imagesJson = objectMapper.writeValueAsString(images);
                    review.setImages(imagesJson);
                } catch (Exception e) {
                    log.error("转换评价图片JSON失败: {}", e.getMessage());
                }
            }

            int result = productReviewMapper.insert(review);
            if (result > 0) {
                log.info("添加商品评价成功，用户ID: {}, 商品ID: {}, 评分: {}", userId, productId, rating);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("添加商品评价失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            throw new RuntimeException("添加商品评价失败");
        }
    }

    @Override
    public Integer countReviewsByProductId(Long productId, Integer status) {
        try {
            return productReviewMapper.countReviewsByProductId(productId, status);
        } catch (Exception e) {
            log.error("统计商品评价数量失败，商品ID: {}", productId, e);
            return 0;
        }
    }

    @Override
    public Double calculateAverageRating(Long productId, Integer status) {
        try {
            Double avgRating = productReviewMapper.calculateAverageRating(productId, status);
            return avgRating != null ? Math.round(avgRating * 10.0) / 10.0 : 0.0;
        } catch (Exception e) {
            log.error("计算商品平均评分失败，商品ID: {}", productId, e);
            return 0.0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditReview(Long reviewId, Integer status) {
        try {
            ProductReview review = productReviewMapper.selectById(reviewId);
            if (review == null) {
                log.warn("评价不存在，评价ID: {}", reviewId);
                return false;
            }

            review.setStatus(status);
            int result = productReviewMapper.updateById(review);
            if (result > 0) {
                log.info("审核评价成功，评价ID: {}, 状态: {}", reviewId, status);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("审核评价失败，评价ID: {}", reviewId, e);
            throw new RuntimeException("审核评价失败");
        }
    }

    /**
     * 转换为评价视图对象
     */
    private ProductReviewVO convertToVO(ProductReview review) {
        try {
            ProductReviewVO vo = new ProductReviewVO();
            vo.setId(review.getId());
            vo.setUserId(review.getUserId());
            vo.setProductId(review.getProductId());
            vo.setRating(review.getRating());
            vo.setContent(review.getContent());
            vo.setStatus(review.getStatus());
            
            if (review.getCreateTime() != null) {
                vo.setCreateTime(review.getCreateTime().format(DATE_FORMATTER));
            }

            // 解析评价图片
            if (review.getImages() != null && !review.getImages().isEmpty()) {
                try {
                    List<String> images = objectMapper.readValue(review.getImages(), new TypeReference<List<String>>() {});
                    vo.setImages(images);
                } catch (Exception e) {
                    log.error("解析评价图片JSON失败: {}", e.getMessage());
                    vo.setImages(new ArrayList<>());
                }
            } else {
                vo.setImages(new ArrayList<>());
            }

            // 设置用户信息
            if (review.getUser() != null) {
                vo.setUsername(review.getUser().getUsername());
                vo.setRealName(review.getUser().getRealName());
                vo.setAvatar(review.getUser().getAvatar());
            }

            return vo;
        } catch (Exception e) {
            log.error("转换评价视图对象失败: {}", e.getMessage(), e);
            return new ProductReviewVO();
        }
    }
}

